package com.ibeeking.found.upms.cp.rest.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ibeeking.found.common.base.BaseDO;
import com.ibeeking.found.common.config.feign.GlobalClient;
import com.ibeeking.found.common.constants.DefaultPathConstant;
import com.ibeeking.found.common.constants.GlobalConstant;
import com.ibeeking.found.common.constants.UserConstant;
import com.ibeeking.found.common.entity.LoginCpUserDTO;
import com.ibeeking.found.common.entity.TenantDTO;
import com.ibeeking.found.common.enums.*;
import com.ibeeking.found.common.enums.LoginModeEnum;
import com.ibeeking.found.common.enums.member.RegisterChannelEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.id.GenerateId;
import com.ibeeking.found.upms.api.common.query.LoginAuthQuery;
import com.ibeeking.found.upms.service.common.query.LogoutAuthQuery;
import com.ibeeking.found.upms.cp.rest.service.ICpUserService;
import com.ibeeking.found.upms.cp.rest.service.ILoginService;
import com.ibeeking.found.upms.cp.rest.service.IWxOpenService;
import com.ibeeking.found.upms.service.common.bo.CpUserRegisterBO;
import com.ibeeking.found.upms.service.common.bo.TenantUserBO;
import com.ibeeking.found.upms.service.common.constants.RedisKeyConstant;
import com.ibeeking.found.upms.service.common.dos.TenantUserDO;
import com.ibeeking.found.upms.service.common.param.*;
import com.ibeeking.found.upms.service.common.query.CpUserRegisterQuery;
import com.ibeeking.found.upms.service.common.query.CpAuthCodeQuery;
import com.ibeeking.found.upms.service.common.query.CpOauth2Query;
import com.ibeeking.found.upms.service.common.vo.*;
import com.ibeeking.found.upms.service.mapper.CpUserMapper;
import com.ibeeking.nematos.constants.enums.LogConstant;
import com.ibeeking.nematos.exception.AuthorizationException;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.redis.annotation.CacheEvict;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.id.IdGenerator;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseCodeEnum;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpOAuth2Service;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUserDetail;
import me.chanjar.weixin.cp.tp.service.WxCpTpOAuth2Service;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @ClassName LoginServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-01-27 18:50
 **/
@Service
public class LoginServiceImpl implements ILoginService {

    private static final String REGISTER_KEY = "REGISTER_KEY:";

    @Resource
    private GlobalClient globalClient;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    @Resource
    private CpUserMapper cpUserMapper;

    @Resource
    private ICpUserService cpUserServiceImpl;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public UrlVO buildPreAuthUrl(CpOauth2Query query){
        Integer tenantId = query.getTenantId();
        if(tenantId == null) tenantId = UserUtils.getTenantID().intValue();
        Integer appType = query.getType();
        String redirectUri = query.getRedirectUri();
        String state = query.getState();
        String oAuth2PreAuthUrl = "";
        if(appType == WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode()) {
            WxCpService wxcpService = wxOpenServiceImpl.getWxCpService(Long.valueOf(tenantId));
            if (null == wxcpService) throw new BusinessException("获取wxcpService 出错");
            WxCpOAuth2Service wxCpOAuth2Service = wxcpService.getOauth2Service();
            if (wxCpOAuth2Service == null) throw new BusinessException("获取WxCpOAuth2Service 出错");
            oAuth2PreAuthUrl =  wxCpOAuth2Service.buildAuthorizationUrl(redirectUri, state, WxConsts.OAuth2Scope.SNSAPI_PRIVATEINFO);
        }else if(appType == WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode()) {
            WxCpTpService wxCpTpService = wxOpenServiceImpl.getWxCpTpService(Long.valueOf(tenantId));
            if (null == wxCpTpService) throw new BusinessException("获取wxCpTpService 出错");
            WxCpTpOAuth2Service wxCpTpOAuth2Service = wxCpTpService.getWxCpTpOAuth2Service();
            if (wxCpTpOAuth2Service == null) throw new BusinessException("获取wxCpTpOAuth2Service 出错");
            oAuth2PreAuthUrl = wxCpTpOAuth2Service.buildAuthorizeUrl(redirectUri, state, WxConsts.OAuth2Scope.SNSAPI_PRIVATEINFO);
        }else if(appType == WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode()) {
            WxCpTpService wxCpTpService = wxOpenServiceImpl.getWxCpTpService(Long.valueOf(tenantId));
            if (null == wxCpTpService) throw new BusinessException("获取wxCpTpService 出错");
            WxCpTpOAuth2Service wxCpTpOAuth2Service = wxCpTpService.getWxCpTpOAuth2Service();
            if (wxCpTpOAuth2Service == null) throw new BusinessException("获取wxCpTpOAuth2Service 出错");
            oAuth2PreAuthUrl = wxCpTpOAuth2Service.buildAuthorizeUrl(redirectUri, state, WxConsts.OAuth2Scope.SNSAPI_PRIVATEINFO);
        }
        return new UrlVO().setUrl(oAuth2PreAuthUrl);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginCpUserDTO queryLoginCpUser(LoginAuthQuery query, String tenantId) {
        LoginCpUserDTO result = null;
        if (LoginModeEnum.WX_CP.getCode().equals(query.getLoginMode())) {
            try {
                if (redisUtils.tryLock(tenantId + query.getOpenId())) {
                    LambdaQueryWrapper<TenantUserDO> queryWrapper = new LambdaQueryWrapper<>(TenantUserDO.class).eq(TenantUserDO::getWxUserId, query.getOpenId());
                    TenantUserDO entityDO = cpUserServiceImpl.selectOneByQueryWrapper(queryWrapper);
                    if (null != entityDO) {
                        result = BeanUtil.convertBean(entityDO, LoginCpUserDTO.class);
                        result.setUserCode(entityDO.getUserCode());
                        result.setPassword(entityDO.getPassword());
                        result.setTenantId(Integer.valueOf(tenantId));
                        result.setWxUserId(entityDO.getWxUserId());
                        result.setDingUserId(entityDO.getDingUserId());
                        result.setLock(!PublishStatusEnum.ENABLE.getValue().equals(entityDO.getPublishStatus()));
                        result.setJob(entityDO.getJob());
                        result.setLoginRole(LoginRoleEnum.WX_CP.name());
                        if(StringUtils.isNotEmpty(tenantId)) {
                            TenantDTO tenantDTO = queryTenantById(Integer.valueOf(tenantId));
                            if(tenantDTO != null){
                                result.setIndustry(tenantDTO.getIndustry());
                            }
                        }
                        List<Long> tIds = new ArrayList<>();
                        tIds.add(Long.valueOf(tenantId));
                        result.setIds(tIds);
                    }
                }
            } finally {
                redisUtils.unlock(tenantId + query.getOpenId());
            }
        }else if(LoginModeEnum.MOBILE.getCode().equals(query.getLoginMode())){
            //微信小程序进行认证登录
            try {
                if (redisUtils.tryLock(tenantId + query.getMobile())) {
                    LambdaQueryWrapper<TenantUserDO> queryWrapper = new LambdaQueryWrapper<>(TenantUserDO.class)
                            .eq(TenantUserDO::getUserCode, query.getMobile()).or().eq(TenantUserDO::getMobile, query.getMobile());
                    TenantUserDO entityDO = cpUserServiceImpl.selectOneByQueryWrapper(queryWrapper);
                    if (null != entityDO) {
                        result = BeanUtil.convertBean(entityDO, LoginCpUserDTO.class);
                        result.setUserCode(entityDO.getUserCode());
                        result.setPassword(entityDO.getPassword());
                        result.setTenantId(Integer.valueOf(tenantId));
                        result.setWxUserId(entityDO.getWxUserId());
                        result.setDingUserId(entityDO.getDingUserId());
                        result.setLock(!PublishStatusEnum.ENABLE.getValue().equals(entityDO.getPublishStatus()));
                        result.setJob(entityDO.getJob());
                        result.setLoginRole(LoginRoleEnum.WX_CP.name());
                        if(StringUtils.isNotEmpty(tenantId)) {
                            TenantDTO tenantDTO = queryTenantById(Integer.valueOf(tenantId));
                            if(tenantDTO != null){
                                result.setIndustry(tenantDTO.getIndustry());
                            }
                        }
                        List<Long> tIds = new ArrayList<>();
                        tIds.add(Long.valueOf(tenantId));
                        result.setIds(tIds);
                    }
                }
            } finally {
                redisUtils.unlock(tenantId + query.getMobile());
            }
        }
        if (null == result) {
            return null;
        }
        return result;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public CpUserRegisterVO loginByAuthorize(CpUserRegisterQuery query) {
        LogUtils.info("CpUserRegisterQuery ={}", JsonUtils.toJsonStr(query));
        CpUserRegisterVO result = new CpUserRegisterVO();
        result.setRegister(true);
        String tenantId = ThreadContext.get(LogConstant.TENANT_ID);
        result.setTenantId(tenantId);
        result.setRegisterChannel(query.getRegisterChannel());
        if (RegisterChannelEnum.WX_CP.name().equalsIgnoreCase(query.getRegisterChannel().name())) {
            if (null == query.getData())  throw new AuthorizationException(HttpStatus.UNAUTHORIZED.value(), "企业微信登录参数不能为空");
            CpAuthCodeQuery authCodeQuery = JsonUtils.fromJson(query.getData(), CpAuthCodeQuery.class);
            if (StringUtils.isBlank(authCodeQuery.getAuthCode()))  throw new AuthorizationException(HttpStatus.UNAUTHORIZED.value(), "企业微信登录临时凭证Code不能为空");
            if (StringUtils.isBlank(authCodeQuery.getAppId()))  throw new AuthorizationException(HttpStatus.UNAUTHORIZED.value(), "企业微信AppId不能为空");
            String appId = authCodeQuery.getAppId();

            WxCpService wxcpService = wxOpenServiceImpl.getWxCpService(Long.valueOf(tenantId));
            if(null == wxcpService) throw new BusinessException("获取wxcpService 出错");
            WxCpOAuth2Service wxCpOAuth2Service = wxcpService.getOauth2Service();
            if(null == wxCpOAuth2Service) throw new BusinessException("获取wxCpOAuth2Service出错");

            try {
                WxCpOauth2UserInfo oauth2UserInfo = wxCpOAuth2Service.getUserInfo(Integer.valueOf(appId),authCodeQuery.getAuthCode());
                LogUtils.info("oauth2UserInfo={}", JsonUtils.toJsonStr(oauth2UserInfo));
                if(oauth2UserInfo == null || StringUtils.isEmpty(oauth2UserInfo.getUserId())){
                    result.setRegister(false);
                } else {
                    String wxUserId = oauth2UserInfo.getUserId();
                    result.setOpenId(wxUserId);
                    String userTicket = oauth2UserInfo.getUserTicket();
                    String ticketExpireIn = oauth2UserInfo.getExpiresIn();
                    WxCpUserDetail cpUserDetail = null;
                    if(StringUtils.isNotEmpty(userTicket)){
                        cpUserDetail = wxCpOAuth2Service.getUserDetail(userTicket);
                        if(null != cpUserDetail && StringUtils.isEmpty(cpUserDetail.getMobile())){
                            authCodeQuery.setMobile(cpUserDetail.getMobile());
                        }
                    }
                    CpWxRegisterDataVO cpWxRegisterDataVO = new CpWxRegisterDataVO();
                    cpWxRegisterDataVO.setWxUserId(wxUserId);
                    result.setDataVO(cpWxRegisterDataVO);
                    CpUserRegisterBO cpUserRegisterBO = null;
                    if (StringUtils.isBlank(authCodeQuery.getMobile())) {
                        List<TenantUserBO> userBos = cpUserServiceImpl.queryLoginCpUserByMobileAndWxUserId(wxUserId, null);
                        LogUtils.info("userBos ={}", JsonUtils.toJsonStr(userBos));
                        if (Collections3.isNotEmpty(userBos)) {
                            if (userBos.size() > 1) {
                                Optional<TenantUserBO> first = userBos.stream().filter(s -> PublishStatusEnum.ENABLE.getValue().equals(s.getPublishStatus())).findFirst();
                                if (first.isPresent()) {
                                    TenantUserBO memberInfoBO = first.get();
                                    //清空别的wxUserId绑定关系
                                    List<Long> ids = userBos.stream().map(TenantUserBO::getId).filter(id -> !id.equals(memberInfoBO.getId())).collect(Collectors.toList());
                                    cpUserServiceImpl.clearWxUserId(ids);
                                }
                            } else {
                                cpUserRegisterBO = BeanUtil.convertBean(userBos.get(0), CpUserRegisterBO.class);
                            }
                        }
                    } else {
                        TenantUserBO memberInfoBO = cpUserServiceImpl.queryByUserCode(authCodeQuery.getMobile());
                        LogUtils.info("memberInfoBO ={}", JsonUtils.toJsonStr(memberInfoBO));
                        if(memberInfoBO != null) {
                            cpUserRegisterBO = BeanUtil.convertBean(memberInfoBO, CpUserRegisterBO.class);
                        }
                    }
                    LogUtils.info("cpUserRegisterBO ={}", JsonUtils.toJsonStr(cpUserRegisterBO));
                    if (null == cpUserRegisterBO) {
                        LogUtils.info("cpUserDetail ={}", JsonUtils.toJsonStr(cpUserDetail));
                        if(cpUserDetail!=null){
                            TenantUserParam userParam = new TenantUserParam();
                            Long newUserId = IdGenerator.getId();
                            userParam.setId(newUserId);
                            userParam.setWxUserId(cpUserDetail.getUserId());
                            userParam.setUserCode(cpUserDetail.getMobile());
                            userParam.setMobile(cpUserDetail.getMobile());
                            userParam.setEmail(cpUserDetail.getEmail());
                            userParam.setImage(cpUserDetail.getAvatar());
                            userParam.setName(StringUtils.isEmpty(cpUserDetail.getName())? UserConstant.ANONYMOUS_USER:cpUserDetail.getName());
                            if(StringUtils.isNotEmpty(cpUserDetail.getGender())) {
                                userParam.setSex(Integer.valueOf(cpUserDetail.getGender()));
                            }
                            userParam.setDescription(GlobalConstant.SYSTEM_OPERATION_DESCRIPTION);
                            LogUtils.info("userParam ={}", JsonUtils.toJsonStr(userParam));
                            cpUserServiceImpl.addTenantUser( Integer.valueOf(tenantId),userParam);
                            result.setOpenId(cpUserDetail.getUserId());
                            result.setCpUserId(newUserId);
                            result.setMobile(cpUserDetail.getMobile());
                        }
                    } else {
                        if (!PublishStatusEnum.ENABLE.getValue().equals(cpUserRegisterBO.getPublishStatus())) {
                            throw new AuthorizationException(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "您已被系统禁止登陆，请联系相关人员");
                        }
                        result.setCpUserId(cpUserRegisterBO.getId());
                        result.setOpenId(cpUserRegisterBO.getWxUserId());
                        result.setMobile(cpUserRegisterBO.getMobile());
                        if (!wxUserId.equals(cpUserRegisterBO.getWxUserId())) {
                            cpUserServiceImpl.modifyWxUserId(wxUserId, cpUserRegisterBO.getId());
                        }
                    }
                }
            } catch (WxErrorException e) {
                LogUtils.error("根据微信授权Code获取用户加密数据失败：[{}]", e.getError().getErrorMsg());
                result.setRegister(false);
            }
        }else if(RegisterChannelEnum.H5_PAGE.name().equals(query.getRegisterChannel().name())) {
            //H5页面渠道
            if (null == query.getData()) {
                throw new AuthorizationException(HttpStatus.UNAUTHORIZED.value(), "H5页面登录参数不能为空");
            }
            CpAuthCodeQuery wxCodeQuery = JsonUtils.fromJson(query.getData(), CpAuthCodeQuery.class);
            if (StringUtils.isBlank(wxCodeQuery.getMobile()))  throw new AuthorizationException(HttpStatus.UNAUTHORIZED.value(), "H5页面登录手机号不能为空");

            H5RegisterVO h5RegisterVO = new H5RegisterVO();
            TenantUserBO entityBO = cpUserServiceImpl.queryByUserCodeOrMobile(wxCodeQuery.getMobile());
            if (null == entityBO) {
                result.setRegister(false);
            } else {
                if (!PublishStatusEnum.ENABLE.getValue().equals(entityBO.getPublishStatus())) {
                    throw new AuthorizationException(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "您已被系统禁止登陆，请联系相关人员");
                }
                h5RegisterVO.setSex(entityBO.getSex());
                result.setOpenId("");
                result.setCpUserId(entityBO.getId());
                result.setMobile(entityBO.getMobile());
                result.setDataVO(h5RegisterVO);
            }
        }

        return result;
    }

    @Override
    public CpUserRegisterVO checkMobile(String mobile) {
        CpUserRegisterVO result = new CpUserRegisterVO();
        result.setRegister(true);
        String tenantId = ThreadContext.get(LogConstant.TENANT_ID);
        result.setTenantId(tenantId);
        if (StringUtils.isBlank(mobile))  throw new BusinessException("手机号不能为空");
        TenantUserBO memberInfoBO = cpUserServiceImpl.queryByUserCode(mobile);
        if (null != memberInfoBO) {
            result.setCpUserId(memberInfoBO.getId());
            result.setMobile(memberInfoBO.getMobile());
        }else{
            result.setRegister(false);
        }
        return result;
    }

    @Override
    public CpUserRegisterVO loginByMobile(CpUserRegisterQuery query) {
        CpUserRegisterVO result = new CpUserRegisterVO();
        result.setRegister(true);
        String tenantId = ThreadContext.get(LogConstant.TENANT_ID);
        result.setTenantId(tenantId);
        result.setRegisterChannel(query.getRegisterChannel());
        if (null == query.getData()) {
            throw new AuthorizationException(HttpStatus.UNAUTHORIZED.value(), "登录参数不能为空");
        }
        CpAuthCodeQuery authCodeQuery = JsonUtils.fromJson(query.getData(), CpAuthCodeQuery.class);
        String mobile = authCodeQuery.getMobile();
        if (StringUtils.isBlank(mobile))  throw new BusinessException("手机号不能为空");
        TenantUserBO memberInfoBO = cpUserServiceImpl.queryByUserCode(mobile);
        if (null != memberInfoBO) {
            result.setCpUserId(memberInfoBO.getId());
            result.setMobile(memberInfoBO.getMobile());
            if (RegisterChannelEnum.WX_CP.name().equalsIgnoreCase(query.getRegisterChannel().name())) {
                CpWxRegisterDataVO cpWxRegisterDataVO = new CpWxRegisterDataVO();
                cpWxRegisterDataVO.setWxUserId(memberInfoBO.getWxUserId());
                result.setOpenId(memberInfoBO.getWxUserId());
                result.setDataVO(cpWxRegisterDataVO);
            } else if (RegisterChannelEnum.ALI_DING.name().equals(query.getRegisterChannel().name())) {
                CpWxRegisterDataVO cpWxRegisterDataVO = new CpWxRegisterDataVO();
                cpWxRegisterDataVO.setWxUserId(memberInfoBO.getWxUserId());
                result.setOpenId(memberInfoBO.getWxUserId());
                result.setDataVO(cpWxRegisterDataVO);
            } else if (RegisterChannelEnum.H5_PAGE.name().equals(query.getRegisterChannel().name())) {
                H5RegisterVO h5RegisterVO = new H5RegisterVO();
                h5RegisterVO.setSex(memberInfoBO.getSex());
                result.setOpenId("");
                result.setDataVO(h5RegisterVO);
            }
        }else{
            result.setRegister(false);
        }
        return result;
    }

    @CacheEvict(cacheName = RedisKeyConstant.CP_USSER_PREFIX, key = "#id")
    @Override
    public Boolean logout(Long id, LogoutAuthQuery query){
        if (RegisterChannelEnum.WX_MA.name().equals(query.getRegisterChannel().name())) {
            //微信渠道
            LambdaUpdateWrapper<TenantUserDO> updateWrapper = new LambdaUpdateWrapper<>();
            if(LoginModeEnum.WX_CP.equals(query.getLoginMode())) {
                updateWrapper.set(TenantUserDO::getWxUserId, "");
            }else if(LoginModeEnum.ALI_DING.equals(query.getLoginMode())) {
                updateWrapper.set(TenantUserDO::getDingUserId, "");
            }
            updateWrapper.eq(BaseDO::getId, id);
            cpUserMapper.update(null, updateWrapper);
            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public CpUserRegisterVO registerNewUser(CpUserRegisterParam param) {
        String tenantId = ThreadContext.get(LogConstant.TENANT_ID);
        if (StringUtils.isBlank(param.getMobile())) throw new BusinessException("手机号不能为空");

        TenantUserBO userInfoBO = cpUserServiceImpl.queryByUserCode(param.getMobile());
        if (null != userInfoBO)  throw new BusinessException("该手机号已注册,请换一个手机号注册或直接登录!");

        if (null == param.getData())  throw new BusinessException("读取用户的注册参数为空");
        TenantUserParam userParam = BeanUtil.convertBean(param.getData(), TenantUserParam.class);
        Long newCpUserId = null == param.getCpUserId() ? GenerateId.generateId() : param.getCpUserId();
        userParam.setId(newCpUserId);
        userParam.setUserCode(param.getMobile());
        userParam.setMobile(param.getMobile());
        userParam.setImage(DefaultPathConstant.DEFAULT_USER_HEAD_IMAGE);
        Boolean newAdd = cpUserServiceImpl.addTenantUser(Integer.valueOf(tenantId), userParam);
        CpUserRegisterVO result = new CpUserRegisterVO();
        result.setRegister(true);
        result.setTenantId(tenantId);
        result.setRegisterChannel(param.getRegisterChannel());
        if(newAdd){
            result.setCpUserId(newCpUserId);
            result.setMobile(param.getMobile());
        }else{
            result.setRegister(false);
        }
        LogUtils.info("会员注册完成 result:" + JSON.toJSONString(result));
        return result;
    }

    @Override
    public LoginCpUserDTO queryUserById(Long id, String tenantId){
        if(id == null) return null;
        TenantUserDO entityDO = cpUserMapper.selectById(id);
        if(entityDO == null) return null;
        LoginCpUserDTO cpUserDTO = new LoginCpUserDTO();
        cpUserDTO.setId(entityDO.getId());
        cpUserDTO.setUserCode(entityDO.getUserCode());
        cpUserDTO.setWxUserId(entityDO.getWxUserId());
        cpUserDTO.setDingUserId(entityDO.getDingUserId());
        cpUserDTO.setName(entityDO.getName());
        cpUserDTO.setNickName(entityDO.getNickName());
        cpUserDTO.setEmail(entityDO.getEmail());
        cpUserDTO.setMobile(entityDO.getMobile());
        cpUserDTO.setJob(entityDO.getJob());
        cpUserDTO.setPublishStatus(entityDO.getPublishStatus());
        if(StringUtils.isNotEmpty(tenantId)) {
            TenantDTO tenantDTO = queryTenantById(Integer.valueOf(tenantId));
            if(tenantDTO != null){
                cpUserDTO.setIndustry(tenantDTO.getIndustry());
                cpUserDTO.setTenantId(Integer.valueOf(tenantId));
            }
        }
        return cpUserDTO;
    }

    @Override
    public LoginCpUserDTO queryUserByOpenId(String openId, String tenantId){
        if(StringUtils.isEmpty(openId)) return null;
        TenantUserDO entityDO = cpUserMapper.selectOne(new LambdaQueryWrapper<TenantUserDO>()
                .eq(TenantUserDO::getWxUserId, openId));
        if(entityDO == null) return null;
        LoginCpUserDTO cpUserDTO = new LoginCpUserDTO();
        cpUserDTO.setId(entityDO.getId());
        cpUserDTO.setUserCode(entityDO.getUserCode());
        cpUserDTO.setWxUserId(entityDO.getWxUserId());
        cpUserDTO.setDingUserId(entityDO.getDingUserId());
        cpUserDTO.setName(entityDO.getName());
        cpUserDTO.setNickName(entityDO.getNickName());
        cpUserDTO.setEmail(entityDO.getEmail());
        cpUserDTO.setMobile(entityDO.getMobile());
        cpUserDTO.setJob(entityDO.getJob());
        cpUserDTO.setPublishStatus(entityDO.getPublishStatus());
        if(StringUtils.isNotEmpty(tenantId)) {
            TenantDTO tenantDTO = queryTenantById(Integer.valueOf(tenantId));
            if(tenantDTO != null){
                cpUserDTO.setIndustry(tenantDTO.getIndustry());
                cpUserDTO.setTenantId(Integer.valueOf(tenantId));
            }
        }
        return cpUserDTO;
    }

    @Override
    public LoginCpUserDTO queryUserByMobileAndOpenId(LoginAuthQuery query, String tenantId){
        if(query == null) return null;
        LambdaQueryWrapper<TenantUserDO> queryWrapper = new LambdaQueryWrapper<>();
        if(LoginModeEnum.WX_CP.equals(query.getLoginMode())) {
            queryWrapper.eq(StringUtils.isNotEmpty(query.getOpenId()), TenantUserDO::getWxUserId, query.getOpenId());
        }else if(LoginModeEnum.ALI_DING.equals(query.getLoginMode())) {
            queryWrapper.eq(StringUtils.isNotEmpty(query.getOpenId()), TenantUserDO::getDingUserId, query.getOpenId());
        }
        queryWrapper.eq(StringUtils.isNotEmpty(query.getMobile()),TenantUserDO::getMobile, query.getMobile());
        TenantUserDO entityDO = cpUserMapper.selectOne(queryWrapper);
        if(entityDO == null) return null;
        LoginCpUserDTO cpUserDTO = new LoginCpUserDTO();
        cpUserDTO.setId(entityDO.getId());
        cpUserDTO.setUserCode(entityDO.getUserCode());
        cpUserDTO.setWxUserId(entityDO.getWxUserId());
        cpUserDTO.setDingUserId(entityDO.getDingUserId());
        cpUserDTO.setName(entityDO.getName());
        cpUserDTO.setNickName(entityDO.getNickName());
        cpUserDTO.setEmail(entityDO.getEmail());
        cpUserDTO.setMobile(entityDO.getMobile());
        cpUserDTO.setJob(entityDO.getJob());
        cpUserDTO.setPublishStatus(entityDO.getPublishStatus());
        if(StringUtils.isNotEmpty(tenantId)) {
            TenantDTO tenantDTO = queryTenantById(Integer.valueOf(tenantId));
            if(tenantDTO != null){
                cpUserDTO.setIndustry(tenantDTO.getIndustry());
                cpUserDTO.setTenantId(Integer.valueOf(tenantId));
            }
        }
        return cpUserDTO;
    }

    private TenantDTO queryTenantById(Integer tenantId) {
        ResponseResult<TenantDTO> responseResult = globalClient.queryTenantById(tenantId);
        if (null == responseResult || null == responseResult.getData()) {
            throw new BusinessException("租户不存在");
        }
        return responseResult.getData();
    }
}
